package com.demo.autotest.service;

import com.demo.autotest.common.exception.DemoException;
import com.demo.autotest.database.domain.Project;
import com.demo.autotest.database.domain.User;
import com.demo.autotest.database.mapper.ProjectMapper;
import com.demo.autotest.database.mapper.UserMapper;
import com.demo.autotest.dto.RoleDTO;
import com.demo.autotest.dto.UserDTO;
import com.demo.autotest.request.QueryRequest;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service    // 定义service层
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private ProjectMapper projectMapper;

    public void saveUser(User user){
        // 验证account、mobile是否已经存在数据库中 todo
        User old1 = userMapper.getUserByAccount(user.getAccount());
        if (old1 != null){
            throw new DemoException("账号已存在～");
        }

        User old2 = userMapper.getUserByAccount(user.getMobile());
        if (old2 != null){
            throw new DemoException("手机号已存在～");
        }

        user.setId(UUID.randomUUID().toString());
        user.setPassword("12345678");
        user.setCreateTime(System.currentTimeMillis());
        user.setUpdateTime(System.currentTimeMillis());
        userMapper.insertUser(user);

    }

    public UserDTO getUserById(String id){
        UserDTO user = userMapper.getUserById(id);
        user.setPassword(null);
        return user;
    }

    public UserDTO getUserByAccount(String account){
        return userMapper.getUserByAccount(account);
    }

    public void deleteUser(String id){
        userMapper.deleteUser(id);
    }

    public void resetPwd(String id){
        userMapper.resetPwd(id);
    }

    public List<Project> getUserProjectList(String userId){
        return projectMapper.getUserProjectList(userId);
    }

    public List<User> getUserAllList(){
        return userMapper.getUserAllList();
    }

    public List<UserDTO> getUserList(QueryRequest request){
        if(request.getCondition() != null && !request.getCondition().equals("")){
            request.setCondition("%" + request.getCondition() + "%");
        }
        return userMapper.getUserList(request);
    }

}
